﻿using AutoMapper;
using B.MES.Customer.Domain;
using B.MES.Customer.Domain.DTO;
using B.MES.Customer.Infrastructure.IRepository;
using Google.Protobuf.WellKnownTypes;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace B.MES.Customer.Infrastructure.Repository
{
    public class RoleRepository: BaseRepository<Role>,IRoleRepository
    {
        private readonly ISqlSugarClient _db;

        private readonly IMapper mapper;
        public RoleRepository(ISqlSugarClient db, IMapper mapper) : base(db)
        {
            _db = db;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加角色信息
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public APIResult<RoleDTO> AddRole(RoleDTO role)
        {
            try
            {
                APIResult<RoleDTO> aPIResult = new APIResult<RoleDTO>();
                var addRole = mapper.Map<Role>(role);

                // 插入新角色信息
                _db.Insertable(addRole).ExecuteCommand();

                // 查询角色信息列表
                var roleList = _db.Queryable<Role>().ToList();

                // 将新增的角色信息插入到列表的最前面
                roleList.Insert(0, addRole);

                aPIResult.Success(200, "添加成功");
                return aPIResult;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 分配权限
        /// </summary>
        /// <param name="rolePermissionDTO">角色权限</param>
        /// <returns>角色权限的数据</returns>
        public APIResult<RolePermissionDTO> AddRolePermission(RolePermissionDTO rolePermissionDTO)
        {
            APIResult<RolePermissionDTO> aPIResult=new APIResult<RolePermissionDTO>();

            var roleId = rolePermissionDTO.RoleId;
            var list = _db.Queryable<Role_Permission>().Where(x => x.Role_Id == roleId).ToList();
            if (list.Count>0)
            {
                _db.Deleteable(list).ExecuteCommand();
            }

            foreach (var item in rolePermissionDTO.Permssions.Split(','))
            {
                Role_Permission role_Permission = new Role_Permission();
                role_Permission.Role_Id = rolePermissionDTO.RoleId;
                role_Permission.Permission_Id = item;
                _db.Insertable(role_Permission).ExecuteCommand();
            }

            aPIResult.Success();
            return aPIResult;
        }

        /// <summary>
        /// 批量删除角色
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public APIResult<List<Role>> BatchDeleteRoles(List<Role> list)
        {
            APIResult<List<Role>> apiResult = new APIResult<List<Role>>();

            try
            {
                // 遍历传入的用户列表，更新每个用户对象的 IsDelete 属性为 true
                foreach (var user in list)
                {
                    user.IsDelete = true;
                }

                // 使用 SqlSugar 的 Updateable 方法批量更新用户对象列表
                _db.Updateable(list).ExecuteCommand();

                // 更新成功后将更新过的用户列表添加到 APIResult 对象中并返回
                apiResult.SuccessDel();
                return apiResult;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 单个删除角色（真删除）
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public APIResult<Role> DeleteRole(int roleId)
        {
            try
            {
                APIResult<Role> aPIResult = new APIResult<Role>();
                _db.Deleteable<Role>(roleId).ExecuteCommand();
                aPIResult.SuccessDel();
                return aPIResult;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改角色信息
        /// </summary>
        /// <param name="role">角色信息</param>
        /// <returns>受影响的行数</returns>
        public APIResult<Role> UpdateRole(Role role)
        {
            var result = new APIResult<Role>();
            try
            {
                _db.Updateable(role).ExecuteCommand();
                result.Success(role);
            }
            catch (Exception ex)
            {
                result.Error(ex.Message);
            }
            return result;
        }

        /// <summary>
        /// 获取角色信息
        /// </summary>
        /// <returns></returns>
        public PageApiResut<Role> GetRole()
        {
            try
            {
                PageApiResut<Role> pageApiResut = new PageApiResut<Role>();
                var list = _db.Queryable<Role>().ToList();
                pageApiResut.TotalCount = list.Count();
                pageApiResut.Data =list;
                return pageApiResut;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 根据角色ID 获取对应的权限ID
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public PageApiResut<string> GetRoleIdByPermissionIds(string roleId)
        {
            try
            {
                PageApiResut<string> pageApiResut = new PageApiResut<string>();
                pageApiResut.Data = _db.Queryable<Role_Permission>().Where(x => x.Role_Id == roleId).Select(x => x.Permission_Id).ToList();
                return pageApiResut;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
